﻿using Signage01.util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Signage01
{
    enum ResourceGraphicsType
    {
        TEXT,
        RSS
    }

    class ResourceGraphicsTimer
    {
        private MainWindow mainWindow;
        private ResourceGraphics resourceToAdd;

        Rectangle rectangle;
        TimelineComponent timelineComponent;
        private ResourceGraphicsType resourceGraphicsType;


        private DispatcherTimer timerStart;
        //private Timer timerStart;
        private DispatcherTimer timerEnd;
        
        private DateTime dateTimeFirst, dateTimeSecond;
        private double passedSecond;

        private Canvas canvasInner;
        private Canvas canvasToAdd;
        private TextBlock textBlock;
        private Storyboard storyboard;
        //update timer
        private DispatcherTimer timerUpdateRSS;

        public ResourceGraphicsTimer(MainWindow mainWindow, ResourceGraphics resourceGraphics, Rectangle rectangle, TimelineComponent timelineComponent)
        {
            // initializin the member variables
            this.mainWindow = mainWindow;
            this.canvasToAdd = this.mainWindow.campaignCanvas;
            this.resourceToAdd = resourceGraphics;
            this.rectangle = rectangle;
            this.timelineComponent = timelineComponent;
            //

            checkResourceGraphicType();
            initializeTimer();
        }


        private void initializeTimer()
        {
            timerStart = new DispatcherTimer();
            //timerStart = new System.Timers.Timer(this.resourceToAdd.Offset*1000);
            //timerStart.SynchronizingObject = this;
            timerStart.Interval = TimeSpan.FromSeconds(this.resourceToAdd.Offset);
            timerStart.Tick += timer_Tick_start;
            //end timer
            timerEnd = new DispatcherTimer();
            //timerEnd = new Timer((this.resourceToAdd.Offset + this.resourceToAdd.Duration)*1000);
            timerEnd.Interval = TimeSpan.FromSeconds(this.resourceToAdd.Offset + this.resourceToAdd.Duration);
            timerEnd.Tick += timer_Tick_end;
            //Thread.Sleep(this.resourceToAdd.Offset * 1000);

            timerStart.IsEnabled = true;
            //Console.WriteLine("timer start started for resource:" + resourceToAdd.LocalFile.FileName);
            timerEnd.IsEnabled = true;
            //Console.WriteLine("timer stop started for resource:" + resourceToAdd.LocalFile.FileName);
            dateTimeFirst = DateTime.Now;
            timerUpdateRSS = new DispatcherTimer();
            timerUpdateRSS.Interval = TimeSpan.FromSeconds(0);
            timerUpdateRSS.Tick += updateRSS;
            timerUpdateRSS.IsEnabled = true;

        }

        void timer_Tick_start(object sender, EventArgs e)
        {
            addResourceToRectangle();
            //Console.WriteLine(resourceToAdd.LocalFile.FileName + " added");
            timerStart.IsEnabled = false;
            //timerStart = null;
        }

        void timer_Tick_end(object sender, EventArgs e)
        {
            removeResourceToRectangle();
            timerEnd.IsEnabled = false;
            this.timelineComponent.deleteResourceGraphicsTimer(this);

        }

        private void addResourceToRectangle()
        {
            rectangle.Opacity = 1;

            if (resourceGraphicsType == ResourceGraphicsType.RSS)
            {
                // creating an inner canvas to add the textblock
                canvasInner = new Canvas();
                canvasInner.Width = this.rectangle.Width;
                canvasInner.Height = this.rectangle.Height;
                Canvas.SetTop(canvasInner, Canvas.GetTop(rectangle));
                Canvas.SetLeft(canvasInner, Canvas.GetLeft(rectangle));
                Canvas.SetZIndex(canvasInner, Canvas.GetZIndex(rectangle));
                canvasToAdd.Children.Add(canvasInner);
                //

                double textBoxWidth;
                textBlock = new TextBlock();
                ResourceRSS resourceRSS = (ResourceRSS)resourceToAdd;
                string str = resourceRSS.StrAllNewsTitles;
                textBlock.Text = str;
                textBlock.FontSize = (double)this.rectangle.Height / 2;
                textBlock.FontWeight = (resourceRSS.IsBold == true) ? FontWeights.Bold : FontWeights.Normal;
                textBlock.TextDecorations = (resourceRSS.IsUnderlined == true) ? TextDecorations.Underline : null;
                textBlock.FontStyle = (resourceRSS.IsItalic == true) ? FontStyles.Italic : FontStyles.Normal;

                double pixelXFactor;
                double canvaswidth = mainWindow.campaignCanvas.Width;
                double negXOffSet = 0;
                double fromSecValue = 0;
                string theText = str;
                double equSlope = 0.022546419;
                double offSetY = 10.96286472;
                double stringSize;

                int textLen = theText.Length;


                //Set the width of the text box according to the width (not length) of the text in it.  

                System.Globalization.CultureInfo enUsCultureInfo;
                Typeface fontTF;
                FormattedText frmmtText;

                if (textLen > 0)
                {
                    enUsCultureInfo = System.Globalization.CultureInfo.GetCultureInfo("en-us");
                    fontTF = new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch);
                    frmmtText = new FormattedText(theText, enUsCultureInfo, FlowDirection.LeftToRight, fontTF, textBlock.FontSize, textBlock.Foreground);

                    stringSize = frmmtText.Width;


                    if (stringSize < 100)
                        pixelXFactor = 1.02;
                    else
                        pixelXFactor = 1.01;

                    textBoxWidth = stringSize * pixelXFactor;

                    textBlock.Width = textBoxWidth;
                    negXOffSet = textBoxWidth * -1;

                    fromSecValue = (stringSize * equSlope) + offSetY;

                    textBlock.Text = theText;

                    canvasInner.Children.Add(textBlock); //rectangle
                    canvasInner.ClipToBounds = true;
                    storyboard = new Storyboard();

                    Duration durX = new Duration(TimeSpan.FromSeconds(fromSecValue));

                    DoubleAnimation daX = new DoubleAnimation(canvaswidth, negXOffSet, durX);
                    daX.RepeatBehavior = RepeatBehavior.Forever;

                    Storyboard.SetTarget(daX, textBlock);
                    Storyboard.SetTargetProperty(daX, new PropertyPath("(Canvas.Left)"));

                    //Storyboard.SetTargetName(daX, "rtTTransform");
                    //Storyboard.SetTargetProperty(daX, new PropertyPath(TranslateTransform.XProperty));

                    storyboard.Children.Add(daX);
                    storyboard.Begin();
                }
            }

        }

        private void removeResourceToRectangle()
        {
            rectangle.Opacity = 0;
            resourceToAdd = null;
            if (resourceGraphicsType == ResourceGraphicsType.RSS)
            {
                textBlock.Text = "";
                storyboard.Remove();
                canvasToAdd.Children.Remove(canvasInner);
                storyboard = null;
            }
            else if (resourceGraphicsType == ResourceGraphicsType.TEXT)
            {
            }
            else
            {

            }

        }

        private void checkResourceGraphicType()
        {
            if (resourceToAdd.GetType() == typeof(ResourceRSS))
            {
                resourceGraphicsType = ResourceGraphicsType.RSS;
            }
            else if (resourceToAdd.GetType() == typeof(ResourceText))
            {
                resourceGraphicsType = ResourceGraphicsType.TEXT;
            }
            else
            {

            }
        }


        public void pause()
        {
            if (storyboard == null)
            {
                if (timerStart.IsEnabled)
                {
                    timerStart.IsEnabled = false;
                }
                if (timerEnd.IsEnabled)
                {
                    timerEnd.IsEnabled = false;
                }
            }
            else
            {
                storyboard.Pause();
                if (timerStart.IsEnabled)
                {
                    timerStart.IsEnabled = false;

                }
                if (timerEnd.IsEnabled)
                {
                    timerEnd.IsEnabled = false;
                }
            }

            dateTimeSecond = DateTime.Now;
            passedSecond = (dateTimeSecond - dateTimeFirst).TotalSeconds;

        }

        public void resume()
        {
            if (storyboard == null)
            {
                if (timerStart.IsEnabled == false)
                {
                    timerStart.Interval = timerStart.Interval - TimeSpan.FromSeconds(passedSecond);
                    timerStart.IsEnabled = true;
                    dateTimeFirst = DateTime.Now;
                }
                if (timerEnd.IsEnabled == false)
                {
                    timerEnd.Interval = timerEnd.Interval - TimeSpan.FromSeconds(passedSecond);
                    timerEnd.IsEnabled = true;
                    dateTimeFirst = DateTime.Now;
                }
            }
            else
            {
                storyboard.Resume();
                /*
                if (timerStart.IsEnabled == false)
                {
                    ResourceRSS rss = (ResourceRSS)resourceToAdd;
                    Console.WriteLine("rss: " + rss.StrAllNewsTitles);
                    timerStart.Interval = timerStart.Interval - TimeSpan.FromSeconds(passedSecond);                        
                    timerStart.IsEnabled = true;

                }
                 */
                if (timerEnd.IsEnabled == false)
                {
                    timerEnd.Interval = timerEnd.Interval - TimeSpan.FromSeconds(passedSecond);
                    timerEnd.IsEnabled = true;
                }
                dateTimeFirst = DateTime.Now;
            }
        }

        public void stop()
        {

        }

        
        public void updateRSS(object sender, EventArgs e)
        {
            if (textBlock != null)
            {
                ((ResourceRSS)resourceToAdd).StrAllNewsTitles = RssUtil.getAllTitlesCombined(((ResourceRSS)resourceToAdd).RssSource);
                string strRSS = ((ResourceRSS)resourceToAdd).StrAllNewsTitles;
                textBlock.Text = strRSS;
                timerUpdateRSS.Interval = TimeSpan.FromSeconds(120);
            }
        }

    }
}
